package com.apes.project.jekunAuto.timeTask.scm;

import com.alibaba.fastjson.JSONObject;
import com.apes.crm.business.model.InsuranceCompany;
import com.apes.crm.business.model.InsuranceCompanyDetail;
import com.apes.crm.business.repository.InsuranceCompanyRepository;
import com.apes.framework.api.DomainService;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.pi.service.PiManager;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.party.repository.PartyRoleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @BelongsProject: apes-server
 * @BelongsPackage: com.apes.project.jekunAuto.timeTask.scm
 * @ClassName: InsuranceCompanySynService
 * @Author: pyb
 * @CreateTime: 2020-04-07 10:13
 * @Description: 保险公司同步
 * @Version: 1.0
 */
@Service("insuranceCompanySynService")
public class InsuranceCompanySynService extends DomainService {
    InsuranceCompanyRepository insuranceCompanyRepository;

    @Autowired
    void setInsuranceCompanyRepository(InsuranceCompanyRepository insuranceCompanyRepository) {
        this.insuranceCompanyRepository = insuranceCompanyRepository;
    }

    PartyRoleRepository partyRoleRepository;

    @Autowired
    void setPartyRoleRepository(PartyRoleRepository partyRoleRepository) {
        this.partyRoleRepository = partyRoleRepository;
    }

    PiManager piManager;

    @Autowired
    void setPiManager(PiManager piManager) {
        this.piManager = piManager;
    }

    /**
     * 保险公司同步(查询)
     *
     * @param request
     * @return
     */
    public void synInsuranceCompany(SimpleRequest request) {
        InsuranceCompany insuranceCompany = request.getO(InsuranceCompany.class);
        JSONObject data = new JSONObject();
        data.put("BXGSID", insuranceCompany.getId());
        data.put("BXGSMC", insuranceCompany.getName());
        data.put("LRR", "新系统同步");
        data.put("BXGSJC", insuranceCompany.getAbbreviation());
        List<InsuranceCompanyDetail> list = insuranceCompany.getInsuranceCompanyDetails()
                .stream().filter(item -> Objects.equals("440100", item.getCity().getId())).collect(Collectors.toList());;
        if (list.size() == 0) {
            return;
        }
        InsuranceCompanyDetail companyDetail = list.get(0);
        if (Objects.nonNull(companyDetail.getClient())) {
            data.put("KHID", companyDetail.getClient().getParty().getOrigin());
            data.put("KHMC", companyDetail.getClient().getName());
        }
        if (Objects.nonNull(companyDetail.getSupplier())){
            data.put("GYSID", companyDetail.getSupplier().getParty().getOrigin());
            data.put("GYSMC", companyDetail.getSupplier().getName());
        }
        data.put("PYM", companyDetail.getAPPCode());


        piManager.synErp("mdmBxgsService.getInsuranceCompany",data);
    }

    public InsuranceCompany saveInsuranceCompany(SimpleRequest request) {
        JSONObject requestJO = request.getJO();
        InsuranceCompany insuranceCompany = insuranceCompanyRepository.findOne(requestJO.getString("BXGSID"));
        if (insuranceCompany == null) {
            insuranceCompany = new InsuranceCompany();
            insuranceCompany.setId(requestJO.getString("BXGSID"));
        }
        insuranceCompany.setName(requestJO.getString("BXGSMC"));
        insuranceCompany.setAbbreviation(requestJO.getString("BXGSJC"));
        if (requestJO.getString("KHID") != null) {
            PartyRole client = partyRoleRepository.findOne(JpaDsl.toCriteriaByEq("role.id", "Customer", "id",replaceKHIDRule(requestJO.getString("KHID")))).orElse(null);
            if (client == null) {
                throw new RuntimeException(String.format("客户[%s][%s]在系统中未定义", requestJO.getString("KHID"), requestJO.getString("KHMC")));
            }
            insuranceCompany.setClient(client);
        }
        if (requestJO.getString("GYSID") != null) {
            PartyRole supplier = partyRoleRepository.findOne(JpaDsl.toCriteriaByEq("role.id", "Supplier", "id", replaceGysidRule(requestJO.getString("GYSID")))).orElse(null);
            if (supplier == null) {
                throw new RuntimeException(String.format("供应商[%s][%s]在系统中未定义", requestJO.getString("GYSID"), requestJO.getString("GYSMC")));
            }
            insuranceCompany.setSupplier(supplier);
        }
        return insuranceCompanyRepository.saveAndFlush(insuranceCompany);
    }

    private String replaceGysidRule(String orginSupplierID) {
        String newCustomId = orginSupplierID;
        if(orginSupplierID != null){
            int tempLength = 6;
            int idLength = orginSupplierID.length();
            if( !orginSupplierID.matches(".*[a-zA-Z].*") && idLength>=8){
                newCustomId = orginSupplierID.substring(idLength - tempLength);
            }
        }
        return newCustomId;
    }

    private String replaceKHIDRule(String oldCustomId){
        String newCustomId = oldCustomId;
        if(oldCustomId != null && !oldCustomId.matches(".*[a-zA-Z].*")){
            newCustomId = oldCustomId.replaceFirst(".","C");
        }
        return newCustomId;
    }
}
